#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <netdb.h>


void exitWithError(char* msg) {
	perror(msg);
	exit(1);
}

int main(int argc, char* argv[]) {
	int sockfd, n;
	struct sockaddr_in serv_addr;
	struct hostent * server;
	char buf[256];
	if (argc < 3) {
		fprintf("usage: %s hostname port", argv[0]);
		exit(1);
	}

	if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
		exitWithError("ERROR create socket");
	}

	if ((server = gethostbyname(argv[1])) == NULL) {
		exitWithError("ERROR no such host");
	}
	bzero((char *) & serv_addr, sizeof(serv_addr));
	serv_addr.sin_family = AF_INET;
	short port = atoi(argv[2]);
	serv_addr.sin_port = htons(port);
	bcopy((char*)server->h_addr, (char *)&serv_addr.sin_addr.s_addr, server->h_length);


	if (connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) { // TODO
		exitWithError("ERROR cannot connect");
	}

	// write
	char send[] = "hello,world";
	if ((n = write(sockfd, send, sizeof(send))) < 0) {
		exitWithError("ERROR cannot write");
	}
	printf("write %s\n", send);

	// read
	bzero(buf, 256);
	if ((n = read(sockfd, buf, 256)) < 0) {
		exitWithError("ERROR cannot read");
	}
	printf("read %s\n", buf);

	exit(0);
}